package com.zzh.myapplication.tools;

import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

/**
 * HTTP请求
 * 支持HTTP、HTTPS请求及混合请求
 * @author jda
 *
 */
public class HttpUtil {
	
	 private static HttpClient clientHttp = null;
	 private static HttpClient clientHttps = null;
	 private static HttpClient clientHttpConcurrency = null;//线程并发
	 
	 
	 public static HttpClient initClientHttp(HttpParams params) {
		 if(clientHttp == null) {
			 clientHttp = new DefaultHttpClient();
		 }
		 return clientHttp;
	 }
	 
	 public static HttpClient initClientHttps(HttpParams params) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException {
		 if(clientHttps == null) {
			 KeyStore trustkeStore = KeyStore.getInstance(KeyStore.getDefaultType());
			 trustkeStore.load(null, null);
			 SSLSocketFactory sSLSocketFactory = new SSLSocketFactory(trustkeStore);
			 sSLSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
			 SchemeRegistry registry = new SchemeRegistry();
			 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			 registry.register(new Scheme("https", sSLSocketFactory, 443));
			 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
			 return new DefaultHttpClient(ccm, params);
		 }
		 return clientHttps;
		 
	 }
	 
//	 public static  HttpClient initHttpClient(HttpParams params, boolean isHttpRequest) throws KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
//		 if(isHttpRequest) {
//			 return initClientHttp(params);
//		 }else {
//			 return initClientHttps(params);
//		 }
//	 }
	 
	/**
	 * 发送POST请求 
	 * @param URL 请求路径
	 * @param bodyEntity  POST请求 数据包包体内容
	 * @param encoding 编码
	 * @param isHttpRequest 是否http请求  是：http请求， 否 ：https 请求
	 * @return 返回请求结果
	 * @throws ClientProtocolException 协议异常
	 * @throws IOException IO读取异常
	 * @throws CertificateException  初始化HTTPS 抛出错误
	 * @throws NoSuchAlgorithmException   初始化HTTPS 抛出错误
	 * @throws KeyStoreException  初始化HTTPS 抛出错误
	 * @throws UnrecoverableKeyException  初始化HTTPS 抛出错误
	 * @throws KeyManagementException  初始化HTTPS 抛出错误
	 */
//	public static String sendHttpPost(String URL, String bodyEntity, String encoding, boolean isHttpRequest) throws ClientProtocolException, IOException, KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
//		String result = null;
//		HttpParams httpParams = new BasicHttpParams();
//		HttpConnectionParams.setConnectionTimeout(httpParams, Content.HTTPREQUESTTIMEOUT);
//        HttpConnectionParams.setSoTimeout(httpParams, Content.HTTPTIMEOUT);
//        HttpClient clientHttps = initHttpClient(httpParams, isHttpRequest);
////        if(clientHttpConcurrency == null){
////       	 SchemeRegistry registry = new SchemeRegistry();
////            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
////            ThreadSafeClientConnManager clientConnManager =  new ThreadSafeClientConnManager(httpParams, registry);
////    	     clientHttpConcurrency =  new DefaultHttpClient(clientConnManager, httpParams);
////        }
//	    HttpPost post = new HttpPost(URL);
//	    post.addHeader("Content-Type", "application/x-www-form-urlencoded");
//	    post.addHeader("Accept", "application/json");
//	    if(JdaApplication.accessTokenResultInfo != null) {
//	        post.addHeader("X-Access-Token", JdaApplication.accessTokenResultInfo.getTokenStr());
//	    }
//	    Log.e("URL参数:" , URL);
//	    Log.e("body参数:" , bodyEntity);
//		StringEntity entity = new StringEntity("input="+ bodyEntity, encoding);
//		post.setEntity(entity);
//		post.setParams(httpParams);
////		HttpResponse response = clientHttpConcurrency.execute(post);
//		HttpResponse response = clientHttps.execute(post);
//		int statusCode = response.getStatusLine().getStatusCode();
//		result =  EntityUtils.toString(response.getEntity(), "UTF-8");
//		Log.e("服务器返回结果:" , " statusCode："+ statusCode + " 数据：" + result);
//		result = judgeResponse(statusCode, result);
//		if("refreshToken".equals(result)) {
//			result = refressToken(WebConnectInfo.POST, URL, null, bodyEntity, encoding, isHttpRequest);
//		}
//		return result;
//	}
	
	
	/**
	 * 发送GET请求 
	 * @param URL 请求路径
	 * @param params GET请求参数
	 * @param encoding  编码
	 * @param isHttpRequest 是否http请求  是：http请求， 否 ：https 请求
	 * @return 返回请求结果
	 * @throws IOException IO读取异常
	 * @throws KeyManagementException 初始化HTTPS 抛出错误
	 * @throws UnrecoverableKeyException 初始化HTTPS 抛出错误
	 * @throws KeyStoreException 初始化HTTPS 抛出错误
	 * @throws NoSuchAlgorithmException 初始化HTTPS 抛出错误
	 * @throws CertificateException 初始化HTTPS 抛出错误
	 */
//	public static String sendHttpGet(String URL, Map<String, Object> params, String encoding, boolean isHttpRequest) throws KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
//		String result = null;
//		//https://localhost:8443/videoNews/NewsManagerServlet?title=10&timelength=10
//		StringBuilder builder = new StringBuilder();
//		builder.append(URL).append("?");
//		if(params != null && !params.isEmpty()) {
//			Log.e("jda", "请求参数:" + params.toString());
//			for(Map.Entry<String, Object> entry : params.entrySet()){
//				if("".equals(entry.getValue()) || entry.getValue() == null){
//					builder.append(entry.getKey() + "=" + null +"&");
//	            }else{
//	            	builder.append(entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), encoding) + "&");
//	            }
//			}
//			builder.deleteCharAt(builder.length()-1);
//		}
//		Log.e("jda", "URL编码请求参数:" + builder.toString());
//		HttpParams httpParams = new BasicHttpParams();
//		HttpConnectionParams.setConnectionTimeout(httpParams, Content.HTTPREQUESTTIMEOUT);
//        HttpConnectionParams.setSoTimeout(httpParams, Content.HTTPTIMEOUT);
//	    HttpClient httpClient = initHttpClient(httpParams, isHttpRequest);
//	    HttpGet get = new HttpGet(builder.toString());
//	    get.addHeader("Content-Type", "application/json;charset=" + encoding);
//	    get.addHeader("Accept", "application/json");
//	    if(JdaApplication.accessTokenResultInfo != null) {
//	    	get.addHeader("X-Access-Token", JdaApplication.accessTokenResultInfo.getTokenStr());
//	    }
//		HttpResponse response = httpClient.execute(get);
//		int statusCode = response.getStatusLine().getStatusCode();
//		result =  EntityUtils.toString(response.getEntity(), "UTF-8");
//		Log.e("服务器返回结果:" , " statusCode："+ statusCode + " 数据：" + result);
//		result = judgeResponse(statusCode, result);
//		if("refreshToken".equals(result)) {
//			result = refressToken(WebConnectInfo.GET, URL, params, null, encoding, isHttpRequest);
//		}
//		return result;
//	}
	
	/**
	 * 发送PUT请求 
	 * @param URL 请求路径
	 * @param bodyEntity  PUT 请求 数据包包体内容
	 * @param encoding 编码
	 * @param isHttpRequest 是否http请求  是：http请求， 否 ：https 请求
	 * @return 返回请求结果
	 * @throws ClientProtocolException 协议异常
	 * @throws IOException IO读取异常
	 * @throws CertificateException  初始化HTTPS 抛出错误
	 * @throws NoSuchAlgorithmException   初始化HTTPS 抛出错误
	 * @throws KeyStoreException  初始化HTTPS 抛出错误
	 * @throws UnrecoverableKeyException  初始化HTTPS 抛出错误
	 * @throws KeyManagementException  初始化HTTPS 抛出错误
	 */
//	public static String sendHttpPut(String URL, String bodyEntity, String encoding, boolean isHttpRequest) throws ClientProtocolException, IOException, KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
//		String result = null;
//		HttpParams httpParams = new BasicHttpParams();
//		HttpConnectionParams.setConnectionTimeout(httpParams, Content.HTTPREQUESTTIMEOUT);
//        HttpConnectionParams.setSoTimeout(httpParams, Content.HTTPTIMEOUT);
//	    HttpClient httpClient = initHttpClient(httpParams, isHttpRequest);
//	    HttpPut put = new HttpPut(URL);
//	    put.addHeader("Content-Type", "application/json;charset=" + encoding);
//	    put.addHeader("Accept", "application/json");
//	    if(JdaApplication.accessTokenResultInfo != null) {
//	    	put.addHeader("X-Access-Token", JdaApplication.accessTokenResultInfo.getTokenStr());
//	    	LogUtil.e("token:" + JdaApplication.accessTokenResultInfo.getTokenStr());
//	    }
//	    LogUtil.e("参数:" + bodyEntity);
//		StringEntity entity = new StringEntity(bodyEntity, encoding);
//		put.setEntity(entity);
//		put.setParams(httpParams);
//		HttpResponse response = httpClient.execute(put);
//		int statusCode = response.getStatusLine().getStatusCode();
//		result =  EntityUtils.toString(response.getEntity(), "UTF-8");
//		LogUtil.e("服务器返回结果:" + " statusCode："+ statusCode + " 数据：" + result);
//		result = judgeResponse(statusCode, result);
//		if("refreshToken".equals(result)) {
//			result = refressToken(WebConnectInfo.PUT, URL, null, bodyEntity, encoding, isHttpRequest);
//		}
//		return result;
//	}
	
	
//	public static String judgeResponse(int statusCode, String result) {
//		if(statusCode >= 200 && statusCode < 300) {
//
//		}else if(statusCode >= 300 && statusCode < 400) {
//
//		}else if(statusCode >= 400 && statusCode < 500) {//客户端错误
//			result = "请求失败，" + "客户端错误";
////			if(statusCode == 401) {
////				result = "refreshToken";
////			}else {
////				try {
////					ErrorResultInfo errorResultInfo = GsonUtils.getMutileBean(result, new TypeToken<ErrorResultInfo>() {}.getType());
////					if(statusCode == 422) {
////						result = "请求失败，" + errorResultInfo.getErrors().get(0).getMessage();
////					}else {
////						result = "请求失败，" + errorResultInfo.getReturnMsg();
////					}
////				} catch (Exception e) {
////					// TODO: handle exception
////					e.printStackTrace();
////					result = "请求失败，解析服务器数据Json异常，请联系开发人员！";
////				}
////			}
//
//		}else if(statusCode >= 500 && statusCode < 600) {//服务器错误
//			try {
//				ErrorResultInfo errorResultInfo = GsonUtils.getMutileBean(result, new TypeToken<ErrorResultInfo>() {}.getType());
//				result = "请求失败，" + errorResultInfo.getReturnMsg();
//			} catch (Exception e) {
//				// TODO: handle exception
//				e.printStackTrace();
//				result = "请求失败，请稍后尝试....";
//			}
//
//		}else {
//			result = "请求失败，服务器返回相应码：" + statusCode + "  " + result;
//			LogUtil.e("服务器返回结果:" + result);
//		}
//		return result;
//	}
	
//	public static String refressToken(String requestMethod, String URL, Map<String, Object> params, String bodyEntity, String encoding, boolean isHttpRequest) {
//		String result = null;
//		try {
//			LogUtil.e("开始刷新token...." );
//			Map<String, Object> parame = new HashMap<String, Object>();
//			if(JdaApplication.accessTokenResultInfo != null) {
//			    parame.put("refreshToken", JdaApplication.accessTokenResultInfo.getRefreshToken());
//			}
//			String refreshBody = JdaApplication.gson.toJson(parame);
//		    String refreshResult = HttpUtil.sendHttpPost(Content.URLREFRESHACCESSTOKEN, refreshBody, encoding, isHttpRequest);
//	    	LogUtil.e("刷新结果...."  + refreshResult);
//		    if(refreshResult == null || refreshResult.indexOf("请求失败，") != -1) {
//		    	LogUtil.e("刷新token失败...." );
//		    	return "请求失败，请稍后尝试....";
//		    }
////		    JdaApplication.accessTokenResultInfo  = GsonUtils.getMutileBean(refreshResult, new TypeToken<AccessTokenResultInfo>() {}.getType());
////		    if(JdaApplication.SharePreferenceService != null) {
////				JdaApplication.SharePreferenceService.setAccessTokenResultInfo(JdaApplication.accessTokenResultInfo);
////			}
//			LogUtil.e("重新请求连接...." );
//			if(WebConnectInfo.GET.equals(requestMethod)){
//				result = HttpUtil.sendHttpGet(URL, params, encoding, isHttpRequest);
//			}else if(WebConnectInfo.POST.equals(requestMethod)){
//				result = HttpUtil.sendHttpPost(URL, bodyEntity, encoding, isHttpRequest);
//			}else if(WebConnectInfo.PUT.equals(requestMethod)){
//				result = HttpUtil.sendHttpPut(URL, bodyEntity, encoding, isHttpRequest);
//			}
//			LogUtil.e("重新请求连接， 连接结果...." + result);
//		} catch (Exception e) {
//			// TODO: handle exception
//			e.printStackTrace();
//			result = "请求失败，请稍后尝试....";
//		}
//		return result;
//	}

}
